<?php
class FacebookController 
	extends Zend_Controller_Action 
{

	public function loginAction()
	{
		$config	= Zend_Registry::get('configuration');
		$appId	= $config->facebook->appId;
		$secret	= $config->facebook->api->secret;
		$session = Zend_Registry::get('session');
//		Zend_Session::rememberMe(86400);// 1 dia
		
		try {
			
//			$fb=new My_Facebook_Api( array('appId' => $appId, 'secret' => $secret));
			$fb=new My_Facebook( array('appId' => $appId, 'secret' => $secret));
//			$fb->setCookieSupport( true );
			if( isset($session->comeBack) ){
	        	$returnTo = $session->comeBack;
	        	unset($session->comeBack);
	        } else {
	        	$returnTo = $_SERVER['HTTP_REFERER'];
	        }
			$fbUserId = $fb->getUser();
			
			if ( $fbUserId ) {
			
				$mapper = Delivery_Model_Factory::mapper( 'Clientes' );
		        $cliente = $mapper->loginFB( $fbUserId );
//		        $cliente = Delivery_Model_Cliente::loginFB( $fbUserId );
		        if ( ! $cliente ){
		        
		        	$fbUser = $fb->api("/me/");
		        	
//		        	if ( Delivery_Model_Cliente::exists( $fbUser['email'] ) ){
		        	if ( $mapper->exists( $fbUser['email'] ) ){
		        	
		        		$this->_helper->MyFlashMessenger->addError( 
		        		
		        			sprintf($this->_helper->Translate("userAlreadyExists"), $fbUser['email'])
		        		
//							"Ya existe un registro para el email:{$fbUser['email']}"
		        		);
		        	
		        	} else {
		        	
		        	
			        	$cliente = new Delivery_Model_Cliente( array(
			        		'email'		=> $fbUser['email'],
		        			'nombre'	=> $fbUser['first_name'],
			        		'apellido'	=> $fbUser['last_name'],
			        		'fbUserId'	=> $fbUserId,
			        		'activo'	=> 1,
			        		'telefono'	=> isset( $fbUser['mobile_phone'])? $fbUser['mobile_phone'] : null
			        	));
			        	
//			        	$cliente->guardar();
			        	$mapper->save( $cliente );
		        	}
		        }
	
		        $session->idCliente = $cliente->idCliente;
		    } else {
		    
		    
		    } 
		} 
		catch (Delivery_Model_Exception $e){
        	$this->getHelper('Log')->exception( $e );
        	$this->_helper->MyFlashMessenger->addError( $this->_helper->Translate($e->getMessage()) );
            return $this->getHelper('Redirector')->gotoRoute(array('action'=>'entrar'), 'cliente');	
        
        }   
        catch (My_Facebook_ApiException $e){
        	$this->getHelper('Log')->exception( $e );
        	$this->_helper->MyFlashMessenger->addError( $this->_helper->Translate('facebookLoginFailed') );
            $this->_redirect( $returnTo );
        
        } catch( Zend_Exception $e){
			$this->getHelper('Log')->exception( $e );
			$this->_helper->MyFlashMessenger->addError( $this->_helper->Translate("applicationError") );
            $this->_redirect( $returnTo );			
		}  
		
		
		$this->_redirect( $returnTo );
		
	}
	

	
}